package Concurent;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by root on 17-6-8.
 * 锁是解决线程安全问题,锁的新写法
 * 读锁和写锁
 */

public class LockDemo3 {
    public static String name = "李雷";
    public static String gender = "男";

    public static void main(String[] args) {
        ReadWriteLock lock = new ReentrantReadWriteLock();
        new Thread(new T19(lock)).start();
        new Thread(new T20(lock)).start();
    }

}

class T19 implements Runnable {
    private ReadWriteLock lock = null;
    public T19(ReadWriteLock lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        while(true){
            lock.writeLock().lock();
            if ("李雷".equals(LockDemo1.name)) {
                LockDemo1.name = "韩梅梅";
                LockDemo1.gender = "女";
            } else {
                LockDemo1.name = "李雷";
                LockDemo1.gender = "男";
            }
            lock.writeLock().unlock();
        }
    }

}

class T20 implements Runnable {
    private ReadWriteLock lock = null;
    public T20(ReadWriteLock lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        while (true) {
            lock.readLock().lock();
            System.out.println(LockDemo1.name + ":" + LockDemo1.gender);
            lock.readLock().unlock();
        }
    }

}